package com.fita.admin.service.client.impl;

import com.demo2do.core.entity.exception.BusinessException;
import com.demo2do.core.persistence.annotation.Dao;
import com.fita.admin.dao.ClientDao;
import com.fita.admin.dao.OrderDao;
import com.fita.admin.dao.PrincipalDao;
import com.fita.admin.entity.search.client.ClientSearch;
import com.fita.admin.entity.security.Login;
import com.fita.admin.service.DataServiceImpl;
import com.fita.admin.service.client.ClientService;
import com.fita.entity.agent.Agent;
import com.fita.entity.client.Client;
import com.fita.entity.principal.Principal;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @description:
 * @author: 11200
 * @date: 2019/6/21
 */
@Service("clientService")
public class ClientServiceImpl extends DataServiceImpl<Client> implements ClientService {

    @Dao
    private ClientDao clientDao;

    @Dao
    private PrincipalDao principalDao;

    @Dao
    private OrderDao orderDao;

    /**
     * 添加客户
     *
     * @param client
     * @param login
     */
    public void addClient(Client client, Login login) throws BusinessException{

        Principal principal = principalDao.load(login.getUsername());

        if (StringUtils.isBlank(client.getPhone())){
            throw BusinessException.newInstance("500", "phone为空");
        }
        Client loadByPhone = clientDao.loadByPhone(client.getPhone());
        if (loadByPhone != null){
            throw BusinessException.newInstance("500", "该联系人电话已存在");
        }

        genericDaoSupport.save(client.create(principal));
    }

    /**
     * 修改
     *
     * @param clientId
     * @param client
     */
    public void edit(Long clientId, Client client) {

        Client load = genericDaoSupport.load(Client.class, clientId);

        load.edit(client);

        genericDaoSupport.update(load);

    }

    /**
     * 绑定代理
     *
     * @param clientId
     * @param agentId
     */
    public void bindAgent(Long clientId, Long agentId) {

        Client client = genericDaoSupport.load(Client.class, clientId);

        Agent agent = genericDaoSupport.load(Agent.class, agentId);

        client.bindAgent(agent);

        genericDaoSupport.update(client);
    }

    /**
     * 计算销售额(分)
     *
     * @param clientId
     * @return
     */
    public int calculateSales(Long clientId) {

        Client client = genericDaoSupport.load(Client.class, clientId);

        Agent agent = client.getAgent();

        int sales = orderDao.sumActualPayPrice(agent);

        return sales;
    }

    /**
     * 导出
     *
     * @param search
     * @return
     */
    public List<Client> export(ClientSearch search) {

        List<Client> list = genericDaoSupport.searchForList(search.buildSentenceTemplate(), search.buildParameters());

        return list;
    }
}
